package qj.tool.db.orientdb;

import java.util.HashMap;

import qj.util.funct.F1;

import com.orientechnologies.orient.core.record.impl.ODocument;

@SuppressWarnings({"unchecked", "rawtypes"})
public class Converter {
	public HashMap<Class<?>, ClassConverter> gaeConverters = new HashMap<Class<?>, ClassConverter>();

	public ODocument toDocument(Object o) {
		return toDocument(o, entityType(o.getClass()));
	}
	
	public ODocument toDocument(Object obj, String kind) {
		ODocument entity = new ODocument(kind);

		return copyToEntity(entity, obj);
	}
	public ODocument copyToEntity(ODocument entity, Object obj) {
		ClassConverter<? extends Object> getSet = getConverter(obj.getClass());
		getSet.ote().e(obj, entity);
		return entity;
	}


	public <A> ClassConverter<A> getConverter(Class<A> clazz) {
		ClassConverter<A> getSet = gaeConverters.get(clazz);
		if (getSet == null) {
			getSet = Analyzer.analyze(clazz, new F1<Class,ClassConverter>() {public ClassConverter e(Class obj) {
				return getConverter(obj);
			}});
			gaeConverters.put(clazz, getSet);
		}
		return getSet;
	}

	public static <A> String entityType(Class<A> clazz) {
		return clazz.getSimpleName();
	}

}